<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :span="6">
                <a-form-item label="属地单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    tree-node-filter-prop="title"
                    v-model="selectedKeys"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="onChangeData"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择部门" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="发包单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    ref="orgTree"
                    :tree-data="unitTree"
                    v-model="selectedKeys1"
                    placeholder="请选择发包单位"
                    allow-clear
                    multiple
                    :max-tag-count="2"
                    :show-search="true"
                    :tree-default-expand-all="false"
                    :tree-checkable="true"
                    :tree-check-strictly="false"
                    :tree-node-filter-prop="title"
                    :replace-fields="replaceFields"
                    :rules="[{ required: true, message: '请选择发包单位'}]"
                    @change="handleOrganNameClick"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange1" :style="{width: '50%'}" v-model="TimeOn"/>
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange2" :style="{width: '50%'}" v-model="TimeEnd"/>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="检查人员" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.UserName" allow-clear placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="4" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_v_all_page')">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false">
        <a-col :span="2" class="search-buttons" style="margin-left: -5px; margin-bottom: 5px;">
          <a-button type="primary" @click="handleExport" :loading="batchExportLoading"><a-icon type="export"/>导出</a-button>
        </a-col>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.qhseXyViolationId"
          :rowSelection="null"
          bordered
        >
          <span slot="action" slot-scope="text, record" style="display: flex; justify-content: space-between; gap: 1px;">
            <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
              <a @click="$refs.detail.edit(record)">
                <a-icon type="file-text" /> 详情
              </a>
            </a-button>
            <a-button size="small" style="color: #1d39c4;background-color: #f0f5ff;border-color: #adc6ff;">
              <a @click="editRecord(record)">
                <a-icon type="edit" /> 编辑
              </a>
            </a-button>
            <a-popconfirm
              placement="topRight"
              title="确认删除？"
              @confirm="() => singleDelete(record)"
            >
              <a-button size="small" style="color: #d4380d;background: #fff2e8;border-color: #ffbb96;">
                <a-icon type="delete" /> 删除
              </a-button>
            </a-popconfirm>
          </span>
        </s-table>
        <detail ref="detail" @ok="handleOk" />
        <editForm ref="editForm" @ok="handleOk" />
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { STable, XCard, XDown } from '@/components'
import editForm from './editForm'
import detail from './detail'
import { Empty } from 'ant-design-vue'
import { QHSEOverLappingViolationDelete, getQHSEXyFbViolationPage, getCrossDownloadExcel } from '@/api/modular/system/QHSEXyViolation'
import { getUnitTree1 } from '@/api/modular/system/violationManage'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
// import editForm from './editForm'
// import detail from './detail'
import moment from 'moment'
import { mapGetters } from 'vuex'
export default {
  components: {
    XDown,
    XCard,
    STable,
    detail,
    editForm
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 查询参数
      queryParam: {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
        OrganizationId: '',
        OrganizationName: '',
        ContractingUnitId: []
      },
      TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
      TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      unitTree: [],
      batchExportLoading: false,
      // 表头
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '检查时间',
          dataIndex: 'checkDate',
          customRender: (text, record) => {
            if (record.checkDate) {
              const dateParts = record.checkDate.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '检查人员',
          dataIndex: 'userName'
        },
        {
          title: '属地单位',
          dataIndex: 'organizationName'
        },
        {
          title: '相关方公司',
          dataIndex: 'violationUserDepart'
        },
        {
          title: '发包单位',
          dataIndex: 'contractingUnitName'
        },
        {
          title: '相关方人员',
          dataIndex: 'violationUserName'
        },
        {
          title: '违章性质',
          dataIndex: 'violationType'
        },
        {
          title: '作业项目',
          dataIndex: 'workItem'
        },
        {
          title: '违章描述',
          dataIndex: 'description',
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 5 ? text.substr(0, 5) + '...' : text}
            </a-tooltip>
          )
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        // console.log('666', this.queryParam)
        return getQHSEXyFbViolationPage(Object.assign(parameter, this.queryParam)).then((res) => {
          // console.log(res.data)
          return res.data
        })
      },
      fabaotree: {
            id: '00'
        },
      selectedKeys: [],
      selectedKeys1: [],
      listDonwload: [],
      title: '',
      // selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      QHSEOrganizationTree: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      secondOraName: {
          id: ''
      }
    }
  },
  created() {
    this.getUnitTree()
    this.getQHSEOrganizationTree()
    this.columns.push({
      title: '操作',
      width: '200px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
  },
  computed: {
      ...mapGetters(['userInfo'])
  },
  methods: {
    editRecord(record) {
      if (record.userId === this.userInfo.userId) {
        this.$refs.editForm.edit(record)
      } else {
        this.$message.warning('当前用户非本条数据的录入者，不可编辑！')
      }
    },
    handleClick() {
      // console.log('111', this.queryParam)
      // console.log(typeof (this.queryParam.ContractingUnitId))
      if ((!this.TimeOn && !this.TimeEnd) || (this.TimeOn && this.TimeEnd)) {
        this.$refs.table.refresh(true)
      } else {
        // 提示用户需要填写完整的时间信息
        this.$message.warning('请填写完整的时间信息')
      }
    },
    onChange1(date, dateString) {
      // console.log(dateString, date)
      if (this.queryParam.TimeEnd && dateString) {
        if (dateString > this.queryParam.TimeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD')
        } else {
          this.queryParam.TimeOn = dateString
        }
      } else {
        this.queryParam.TimeOn = dateString
      }
    },
    onChange2(date, dateString) {
      if (this.queryParam.TimeOn && dateString) {
        if (this.queryParam.TimeOn > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
      }
    },
    statusFilter (status) {
        // eslint-disable-next-line eqeqeq
        const values = this.QHSEOrgnizationTree.filter(item => item.code === status)
        if (values.length > 0) {
          return values[0].value
        }
    },
    handleExport(parameter) {
    this.batchExportLoading = true
    // console.log(this.queryParam.ContractingUnitId)
    // 检查 this.queryParam.ContractingUnitId 是否为空
    if (this.queryParam.ContractingUnitId.length !== 0) {
      this.listDonwload = JSON.parse(this.queryParam.ContractingUnitId)
      this.queryParam.ContractingUnitId = this.listDonwload
    }

    // 调用 getCrossDownloadExcel 方法
    getCrossDownloadExcel(Object.assign(parameter, this.queryParam))
      .then(response => {
        // 创建下载链接
        const downloadLink = document.createElement('a')
        downloadLink.href = window.URL.createObjectURL(response.data)
        // 设置下载链接的属性
        downloadLink.download = '相关方违章_' + new Date().toISOString() + '.xlsx'
        downloadLink.target = '_blank'
        // 在下载链接的 click 事件处理程序中停止加载状态
        downloadLink.addEventListener('click', () => {
          this.batchExportLoading = false
        })
        // 触发下载
        downloadLink.click()
      })
      .catch(error => {
        console.error('下载失败:', error)
        this.batchExportLoading = false
      })
    },
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
        })
      },
      getUnitTree () {
        // console.log(this.secondOraName)
        getUnitTree1(Object.assign(this.fabaotree)).then(res => {
          this.treeLoading = false
          this.unitTree = res.data
        })
        this.visible = false
      },
      handleOrganNameClick(value) {
      this.selectedKeys1 = value
      const extractedValues = JSON.stringify(this.selectedKeys1)
      this.queryParam.ContractingUnitId = extractedValues
      console.log('ContractingUnitIdList:', this.queryParam.ContractingUnitId)
    },
    onChangeData(value, label, extra) {
      // console.log(extra)
      if (extra.triggerNode === undefined) {
        this.queryParam.OrganizationName = ''
        this.queryParam.OrganizationId = ''
      } else {
        this.queryParam.OrganizationName = extra.triggerNode._props.title
        this.queryParam.OrganizationId = extra.triggerNode._props.value
        this.selectedKeys = extra.triggerNode._props.title
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    // onSelectChange(selectedRowKeys, selectedRows) {
    //   this.selectedRowKeys = selectedRowKeys
    //   this.selectedRows = selectedRows
    // },
    /**
     * 单个删除
     */
    singleDelete(record) {
      console.log(record.checkOrganizationId)
      console.log(this.userInfo.currentOrganizationId)
      if (record.userId === this.userInfo.userId) {
        const param = [{ 'id': record.qhseXyViolationId }]
        this.QHSEOverLappingViolationDelete(param)
      } else {
        this.$message.warning('当前用户非本条数据的录入者，不可删除！')
      }
    },
    /**
     * 删除违章记录
     */
     QHSEOverLappingViolationDelete(param) {
      QHSEOverLappingViolationDelete(param)
        .then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    reset() {
      this.queryParam = {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD')
      }
      this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
      this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
      this.selectedKeys = []
      this.selectedKeys1 = []
    }
  }
}
</script>
<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
}
/deep/.ant-table-tbody tr:nth-child(2n)
 {
  background-color:#f5f5f5;
 }
/deep/.ant-table {
  border: 1px solid rgb(228, 228, 228);
}

/deep/.ant-table thead > tr:first-child th {
  border-top: none;
}

/deep/.ant-table thead th:last-child,
/deep/.ant-table tbody td:last-child {
  border-right: none;
}

/deep/.ant-table tbody > tr:last-child td {
  border-bottom: none;
}
</style>
